package com.hmdp.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisLock {
    private StringRedisTemplate redisTemplate;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public RedisLock(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    //加锁
    public boolean islLock(String lockPre){
        String key="redis:"+lockPre;
        //写入自己的线程
        long threadId = Thread.currentThread().getId();

        return  redisTemplate.opsForValue()
                .setIfAbsent(key, Long.toString(threadId), 10, TimeUnit.MINUTES);
    }
    //解锁
    public void unLock(String lockPre){
        String key="redis:"+lockPre;
        //取出自己的线程id
        String cahceId = redisTemplate.opsForValue().get(key);
       /* long threadId = Thread.currentThread().getId();
        String idStr = String.valueOf(threadId);
        if(idStr.equals(cahceId)){
            return ;
        }
        redisTemplate.delete(key);*/
        //使用lua脚本进行对应的编写
       redisTemplate.execute(UNLOCK_SCRIPT,
               Collections.singletonList(key),
               cahceId);
    }

}
